﻿using SimpleRssReader.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml;
using Windows8Accelerator.Core.Xaml.Caching;
using Windows8Accelerator.Core.Xaml.Controls;

namespace SimpleRssReader.DataSources
{
    public class CachedDataSource
    {
        private static TimeSpan CACHE_EXPIRATION = new TimeSpan(0,0,1);

        private IDataSource _DataSource;
        
        public CachedDataSource(IDataSource dataSource)
        {
            _DataSource = dataSource;
        }

        public async Task<CachedObject<ObservableCollection<Blog>>> RetrieveBlogsWithLatestPostsAsync(int maxPostsPerBlog)
        {
            using (ProgressBarManager.NewWork())
            {
                return await CacheManager.GetOrRetrieveAsync(string.Format("RetrieveBlogsWithLatestPostsAsync_{0}", maxPostsPerBlog), () => _DataSource.RetrieveBlogsWithLatestPostsAsync(maxPostsPerBlog), CACHE_EXPIRATION);
            }
        }

        public async Task<CachedObject<ObservableCollection<Post>>> RetrieveLatestPostsAsync(Blog blog, int maxPosts)
        {
            using (ProgressBarManager.NewWork())
            {
                return await CacheManager.GetOrRetrieveAsync(string.Format("RetrieveLatestPostsAsync_{0}_{1}", blog.Id, maxPosts), () => _DataSource.RetrieveLatestPostsAsync(blog, maxPosts), CACHE_EXPIRATION);
            }
        }

        public async Task<CachedObject<Post>> RetrieveFullPostAsync(Post post)
        {
            using (ProgressBarManager.NewWork())
            {
                return await CacheManager.GetOrRetrieveAsync(string.Format("RetrieveFullPostAsync_{0}", post.Id), () => _DataSource.RetrieveFullPostAsync(post), CACHE_EXPIRATION);
            }
        }
    }
}
